package com.budwk.app.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

/**
 * @program: dfxy-community-dev
 * @description: RSA工具
 * @author: LJT
 * @create: 2024-05-16 18:53
 **/
public class RSAUtil {
        /**
         * RSA加密
         * @param publicKeyStr 公钥字符串
         * @param plainText 明文字符串
         * @return 加密后的字符串
         * @throws Exception
         */
        public static String encryptByPublicKey(String publicKeyStr, String plainText) throws Exception {
            // 将公钥字符串转换为公钥对象
            byte[] publicKeyBytes = Base64.decodeBase64(publicKeyStr);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);

            // 对明文进行加密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] plainTextBytes = plainText.getBytes("UTF-8");
            byte[] encryptedBytes = cipher.doFinal(plainTextBytes);

            // 将加密后的字节数组转换为字符串
            return Base64.encodeBase64String(encryptedBytes);
        }
}
